<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/dbConnection.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';

class ResourceDao {
	private $_db;

	public function __construct() {
		$this->_db = new DbConnection();
		$this->_db->connect();
	}
	
	/**
	 *
	 * Add a user to the database
	 * @param $user: an instance of UserModel object
	 */
	public function addResource($res) {
		$query = sprintf("CALL sp_AddResource('%s', '%s', '%d', @ResourceId)", 
					mysql_real_escape_string($res->getResourceName()),
					mysql_real_escape_string($res->getShortDescription()),
					$res->getCreatedDate());
					
		$result = $this->_db->executeQuery($query);
		$result = $this->_db->executeQuery("SELECT @ResourceId");

		if (!$result) {
		    echo 'Could not run query: ' . ' ' . mysql_error();
		    return 0;
		}		
		
		if ($row = mysql_fetch_assoc($result)) {
			$id = $row['@ResourceId'];
		}

		mysql_free_result($result);
		
		return $id;		
	}
	
	/*
	 * Delete resource knows its id
	 * returns true if delete successfully
	 * returns false if can't delete
	 */
	public function deleteResource($resID) {
		$query = sprintf("CALL sp_DeleteResource('%u')", $resID);
		
		$result = $this->_db->executeQuery($query);		
		
		if (!$result) {			
			echo 'Could not run query: ' . ' ' . mysql_error();
		    return;
		}
		
		$row = mysql_affected_rows();
		
		mysql_free_result($result);
		
		return ($row != 0);
	}
	
/*
	 * Get resource knows its id
	 * returns resource model if can find
	 * returns null
	 */
	public function getResource($resID) {
		$query = sprintf("SELECT * FROM resources WHERE ResourceId = '%u'", $resID);
		
		$result = $this->_db->executeQuery($query);
		
		if (!$result) {			
			echo 'Could not run query: ' . ' ' . mysql_error();
		    return;
		}
		
		if ($row = mysql_fetch_assoc($result)) {			
			$resource = ResourceDao::getResourceFromFetchRow($row);

			mysql_free_result($result);
		
			return $resource;
		}		
		
	}
	
	public static function getResourceFromFetchRow($row) {
		$resource = new ResourceModel();
		
		$resource->setResourceID($row['ResourceId']);
		$resource->setResourceName($row['FileName']);
		$resource->setShortDescription($row['ShortDescription']);
		$resource->setCreatedDate($row['CreatedDate']);
		
		return $resource;
	}
}
?>